<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Model\Content;

class ContentController extends Controller
{
  // 获取内容列表
  public function getContentList(Request $request, $cid = 0)
  {
    $pagenum = $request->get('pagenum', 1);
    $pagesize = $request->get('pagesize', 10);
    // 计算便宜数据条数
    $offset = ($pagenum - 1) * $pagesize;
    if ($cid) {
      $data = Content::orderBy('status', 'desc')->where('cid', $cid)->offset($offset)->limit($pagesize)->get();
      // 获取数据条数
      $total = $data->count();
    } else {
      $data = Content::orderBy('status', 'desc')->offset($offset)->limit($pagesize)->get();
      // 获取总数据条数
      $total = Content::count();
    }
    // 获取所属栏目名称
    foreach ($data as $v) {
      $v['cateName'] = $v->category->name;
    }
    return response()->json(['status' => 200, 'data' => $data, 'total' => $total]);
  }

  // 根据id获取内容
  public function getContentById($id)
  {
    $data = Content::where('id', $id)->first();
    if (!$data) return response()->json(['status' => 400, 'msg' => '获取内容失败']);
    // 获取cid对应栏目的pid
    $pid = $data->category->pid;
    $cid = $data->cid;
    $cateId = [];
    if ($pid === 0) {
      $cateId[] = $cid;
    } else {
      $cateId[] = $pid;
      $cateId[] = $cid;
    }

    // 修改当前内容的cid
    $data->cid = $cateId;
    return response()->json(['status' => 200, 'data' => $data, 'msg' => '获取内容成功']);
  }

  // 添加内容
  public function addContent(Request $request)
  {
    // 获取所有参数
    $content = $request->all();
    // 将获取到的数据添加到数据表中
    $res = Content::create($content);
    // 判断添加是否成功
    if (!$res) return response()->json(['status' => 400, 'msg' => '添加内容失败']);
    return response()->json(['status' => 200, 'msg' => '添加内容成功']);
  }

  // 删除内容
  public function removeContentById($id)
  {
    $res = Content::where('id', $id)->delete();
    if (!$res) return response()->json(['status' => 400, 'msg' => '删除内容失败']);
    return response()->json(['status' => 200, 'msg' => '删除内容成功']);
  }

  // 修改内容
  public function updateContentById(Request $request, $id)
  {
    // 获取所有参数
    $data = $request->all();
    // 根据id修改内容信息
    $res = Content::where('id', $id)->update($data);
    // 判断修改是否成功
    if (!$res) return response()->json(['status' => 400, 'msg' => '修改内容失败']);
    return response()->json(['status' => 200, 'msg' => '修改内容成功']);
  }
}
